from telethon import events
from telethon.tl.custom import file
from models.uploader import Uploader, Payload
from models.group_store import GroupStore
import logging, tempfile, os
from utils.auto_retry import auto_retry
from config import PHONE

log = logging.getLogger(__name__)

media_types = {"article/", "audio/", "file/","photo/","video/", "voice/", "document/", "application/", "image/"}

def register_handlers(client, groups, uploader: Uploader, store: GroupStore):
    print(f"[DEBUG] 进入函数: register_handlers")
    print(f"[DEBUG] 展示群组/频道: {groups}")
    @client.on(events.NewMessage(chats=[g['id'] for g in groups]))
    async def handler(event):
        print(f"[DEBUG] 进入函数: handler (message event)")
        print(f"[DEBUG] 进入函数: message是:{event.message.message}")
        print(f"[DEBUG] 进入函数: chat_id是:{event.chat_id}")
        try:
            group = next((g for g in groups if g['id'] == event.chat_id), None)
            if not group:
                print(f"[DEBUG] 未找到群组/频道 ID: {event.chat_id}")
                return
            
            group_type = group.get('type', '群组')
            print(f"[DEBUG] 处理来自{group_type}的消息: {group['title']}")
            msg = event.message
            if msg.id <= group['baseline']:
                return  # 历史消息过滤
            store.update_baseline(group['id'], msg.id)

            bot_me = await client.get_me()
            sender = await msg.get_sender()
            base = Payload(
                # tel_phone_number=str(bot_me.id),
                tel_phone_number=PHONE,
                group_id=group['id'],
                group_name=group['title'],
                sender_name=getattr(sender, 'first_name', '未知'),
                sender_id=sender.id,
                send_at=msg.date.replace(tzinfo=None).isoformat(),
                media_type='text',
                content= ''
            )
            # 1. 纯文字直接处理
            if not msg.media:
                if not msg.message or len(msg.message.strip()) <= 1:
                    # 空或单字符丢弃
                    return
                # 去掉换行和回车
                base.content = msg.message.replace('\n', '').replace('\r', '')
                print(f"[DEBUG] 展示上传信息text: {base}")
                uploader.send(base)

            # 2. 带媒体才继续
            if not msg.file:
                return
            mime_type = msg.file.mime_type or ''
            if not any(mime_type.startswith(mt) for mt in media_types):
                return

            print(f"[DEBUG] 展示上传信息media1: {msg.file}")
            print(f"[DEBUG] 展示上传信息media1: {msg.file.mime_type}")
            with tempfile.NamedTemporaryFile(delete=False) as tmp:
                await msg.download_media(file=tmp.name)
                url = uploader.upload_media(tmp.name)
                os.remove(tmp.name)
                log.debug('uploaded %s', url)
                base.media_type = msg.file.mime_type
                base.content = url
            print(f"[DEBUG] 展示上传信息media2: {base}")
            uploader.send(base)

        except Exception as e:
            log.exception('handle message error: %s', e)